import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.Alert;
import javafx.scene.control.TextInputDialog;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import java.util.Optional;



public class Main extends Application {
    private GameEngine gameEngine;
    private Stage primaryStage;
    private Scene menuScene;
    private Scene gameScene;
    private Scene settingsScene;// 设置场景
    private String currentPlayerName;//当前玩家
    boolean isNewGame = false;
    private StoryScene storyScene;


    @Override
    public void start(Stage primaryStage) {
        try {
            // 初始化音乐管理器
            MusicManager.initialize();

            this.primaryStage = primaryStage;

            // 初始化场景
            refreshAllScenes();
            // 加载图标文件
            Image icon = new Image(getClass().getResourceAsStream("/images/app_icon.png"));
            // 设置窗口图标
            primaryStage.getIcons().add(icon);
            // 设置初始场景和舞台
            primaryStage.setScene(menuScene);
            primaryStage.setTitle("魔女的修行");
            primaryStage.setResizable(false);
            primaryStage.show();

            // 播放主菜单音乐
            MusicManager.playMenuMusic();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 刷新所有场景
    private void refreshAllScenes() {
        menuScene = createMenuScene();
        settingsScene = createSettingsScene();
        gameScene = createGameScene();
    }

    private Scene createSettingsScene() {
        SettingsMenu settingsMenu = new SettingsMenu(primaryStage);
        Scene scene = new Scene(settingsMenu,
                GameConstants.getScreenWidth(),
                GameConstants.getScreenHeight());

        // 设置返回按钮事件 - 更新为刷新主菜单
        settingsMenu.getBackButton().setOnAction(e -> {
            // 保留当前全屏状态
            boolean wasFullScreen = primaryStage.isFullScreen();

            // 刷新主菜单场景
            menuScene = createMenuScene();
            primaryStage.setScene(menuScene);

            // 确保窗口居中
            primaryStage.sizeToScene();

            if (wasFullScreen) {
                primaryStage.setFullScreen(true);
            }

        });

        // 分辨率选择事件处理
        settingsMenu.getResolution2().setOnAction(e -> setResolution(960, 540));
        settingsMenu.getResolution3().setOnAction(e -> setResolution(1280, 720));
        return scene;
    }

    private Scene createMenuScene() {
        MainMenu mainMenu = new MainMenu();
        Scene scene = new Scene(mainMenu,
                GameConstants.getScreenWidth(),
                GameConstants.getScreenHeight());

        //刷新排行榜
        mainMenu.updateScoreboard();

        mainMenu.setNewGameButtonAction(e -> {
            TextInputDialog dialog = new TextInputDialog();
            dialog.setTitle("新游戏");
            dialog.setHeaderText("请输入玩家名字");
            dialog.setContentText("名字:");

            Optional<String> result = dialog.showAndWait();
            result.ifPresent(name -> {
                currentPlayerName = name;
                PlayerDataManager.savePlayerName(name);
                isNewGame = true;  // 设置为新游戏
                startNewGame();
            });
        });

        mainMenu.setContinueButtonAction(e -> {
            currentPlayerName = PlayerDataManager.loadPlayerName();
            if (currentPlayerName != null) {
                startNewGame();

            } else {
                // Show alert if no saved player
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("继续游戏");
                alert.setHeaderText(null);
                alert.setContentText("没有找到玩家数据，请开始新游戏");
                alert.showAndWait();
            }
        });

        mainMenu.setSettingsButtonAction(e -> {
            settingsScene = createSettingsScene(); // 总是创建新的设置场景
            primaryStage.setScene(settingsScene);
        });

        mainMenu.setExitButtonAction(e -> primaryStage.close());

        // 确保在返回主菜单时播放主菜单音乐
        MusicManager.playMenuMusic();

        return scene;
    }

    private Scene createStoryScene() {
        // 如果storyScene还未初始化，则创建它
        if (storyScene == null) {
            storyScene = new StoryScene(primaryStage, this);
        }
        return storyScene.createStoryScene();
    }

    void startNewGame() {
        if (isNewGame) {
            // 显示故事场景
            Scene storyScene = createStoryScene();
            primaryStage.setScene(storyScene);
        } else {
            // 直接开始游戏
            gameScene = createGameScene();
            primaryStage.setScene(gameScene);
            gameEngine.startGame();
        }
    }

    private Scene createGameScene() {
        Pane root = new Pane();
        Canvas canvas = new Canvas(
                GameConstants.getAdjustedScreenWidth(),
                GameConstants.getAdjustedScreenHeight()
        );
        root.getChildren().add(canvas);

        // 创建游戏引擎，传入root
        gameEngine = new GameEngine(canvas, root);

        // 创建场景
        Scene scene = new Scene(root);

        // 设置键盘控制
        setupGameControls(scene);

        // 开始游戏时播放游戏音乐
        MusicManager.playGameMusic();

        return scene;
    }

    // 修改setupGameControls方法
    private void setupGameControls(Scene scene) {
        scene.setOnKeyPressed(e -> {
            if (e.getCode() == KeyCode.SPACE || e.getCode() == KeyCode.W) {
                gameEngine.getPlayer().setJumpKeyPressed(true);
                if (!gameEngine.isGameOver() && !GameConstants.GAME_PAUSED) {
                    gameEngine.playerJump();
                }
            }
            else if (e.getCode() == KeyCode.S && !gameEngine.isGameOver() && !GameConstants.GAME_PAUSED) {
                gameEngine.getPlayer().slide();
            }
            else if (e.getCode() == KeyCode.K && !gameEngine.isGameOver() && !GameConstants.GAME_PAUSED) {
                if(gameEngine.getPlayer().getBombAcount() > 0){
                    gameEngine.getPlayer().throwBomb();
                    gameEngine.getPlayer().setBombAcount();
                }
            }
            if (e.getCode() == KeyCode.SPACE && !gameEngine.isPlayerJumping() && !gameEngine.isGameOver() && !GameConstants.GAME_PAUSED) {
                gameEngine.playerJump();
            } else if (e.getCode() == KeyCode.R && gameEngine.isGameOver()) {
                gameEngine.resetGame();
                gameScene = createGameScene();
                primaryStage.setScene(gameScene);
                gameEngine.startGame();
            }  else if (e.getCode() == KeyCode.ESCAPE) {
                if (gameEngine.isGameOver()) {
                    menuScene = createMenuScene();
                    primaryStage.setScene(menuScene);
                } else {
                    gameEngine.togglePause();
                }
            } else if (e.getCode() == KeyCode.SPACE && !gameEngine.isGameOver() && !GameConstants.GAME_PAUSED) {
                gameEngine.getPlayer().setSliding(true);
            }
        });

        scene.setOnKeyReleased(e -> {
            if (e.getCode() == KeyCode.SPACE || e.getCode() == KeyCode.W) {
                gameEngine.getPlayer().setJumpKeyPressed(false);
                if (gameEngine.isPlayerJumping() && !gameEngine.isGameOver() && !GameConstants.GAME_PAUSED) {
                    gameEngine.getPlayer().endJump();
                }
            }
            else if (e.getCode() == KeyCode.S || e.getCode() == KeyCode.X) {
                gameEngine.getPlayer().setSliding(false);
            }
        });
    }

    // 新添加的分辨率设置方法
    private void setResolution(int width, int height) {
        GameConstants.setScreenSize(width, height);
        primaryStage.setWidth(width);
        primaryStage.setHeight(height);
        primaryStage.setFullScreen(false);
        // 刷新所有场景
        refreshAllScenes();

        // 如果当前在设置界面，重新加载设置界面
        if (primaryStage.getScene() == settingsScene) {
            primaryStage.setScene(settingsScene);
        }

        //强制调整画面
        primaryStage.sizeToScene();

    }

    public static void main(String[] args) {
        launch(args);
    }
}